package isquirrel;

import isquirrel.beans.YouTubeVideo;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Vector;

import com.google.gdata.client.youtube.YouTubeService;

public class YouTubeAPI {

	private String _devkey = "AI39si5Firc06-Ce1q_Nqk6uXkmmAr_1Fs1XK7a8ZWlevKzuctZKM22rlQSUHIFpg2wj6QWkeaeX_G1zOkq1oRbigW691dTU4A";
	private YouTubeService _service = null;
	
	private YouTubeCollection _ytcollection = null;

	public static final int AND_KEYWORDS = 1;
	public static final int OR_KEYWORDS = 2;

	public YouTubeAPI(){
		
		_service = new YouTubeService(this._devkey);
		_ytcollection = new YouTubeCollection();
	}
	
	public Vector<YouTubeVideo> getVideosByKeywords(ArrayList<String> keywords, int searchType, int page) throws MalformedURLException, UnsupportedEncodingException{
				
		int keywords_length = keywords.size();

		for (int i = 0; i < keywords_length; ++i){
			
			/* spawn thread to fetch  youtube videos */
			Thread worker = new Thread(new YouTubeWorker(this._service, this._ytcollection,keywords.get(i),searchType,page));
			worker.start();
			this._ytcollection.incrementWorkers();
		}
		
		/* while workers not done give up the processor */
		while (!this._ytcollection.workersDone()){
			 try {
			        Thread.sleep(100);
			 }
			 catch (InterruptedException exc) {
	         }	
		}
		
		Vector<YouTubeVideo> videos = this._ytcollection.videos();
		Collections.shuffle(videos);
		videos.setSize(12);
		return videos;

	}
	
}
